package cn.apienvrypt.util;

import java.lang.reflect.Type;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

/**
 * @author admin
 */
public class GsonUtil {
	private static final GsonBuilder gsonBuilder = new GsonBuilder();

	static {
		gsonBuilder.enableComplexMapKeySerialization();
		gsonBuilder.serializeNulls();
	}

	private GsonUtil() {
	}

	public static Gson getGson() {
		return gsonBuilder.create();
	}

	public static JsonObject stringToGsonObject(String str) {
		return JsonParser.parseString(str)
			.getAsJsonObject();
	}

	public static <T> T parseData(String data, Class<T> classOfT) {
		T result = null;
		if(data != null) {
			try {
				result = getGson().fromJson(data, classOfT);
			} catch(Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 多用于解析
	 *
	 * @param data    data
	 * @param typeOfT new TypeToken(Class){}.getType()
	 * @return T
	 */
	public static <T> T parseData(String data, Type typeOfT) {
		T result = null;
		if(data != null) {
			Gson gson = getGson();
			try {
				result = gson.fromJson(data, typeOfT);
			} catch(Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}
}